var frontBaseUrl = "http://localhost:5500";
var backBaseUrl = "http://localhost:8080";
var blockId = 0;
var clazzId = 0;
var search_data={blockId:blockId,clazzId:clazzId};
var uid = -1;
var user = null;
var editor;



function checkIfUserBanned(id) {
    console.log(blockId)
    console.log("blokidis" + blockId)
    $.post({
        url:'http://localhost:8080/authority/checkUserBanned',
        data:{
            "userId": id,
            "blockId": blockId
        },success: function (msg){
            let ban = msg.data.banList
            if(ban !== undefined && ban !== null &&ban.length !== 0){
                $("#new-post-div").html("<span id='banned-tip'>您已被禁言到" + ban[0].endTime +"====</span>")
            }
        }
    })
}
// 好像因为网页太大不会加载onload？

function loadEditor() {
     window.editor = editormd("editor", {
        width: "100%",
        height: "400px",
        placeholder: "输入发帖内容",
        path: "../../lib/editor.md/lib/",  // Autoload modules mode, codemirror, marked... dependents libs path
        saveHTMLToTextarea: true,
         imageUpload:true,
         imageFormats:["jpg","jpeg","gif","png","bmp","webp"],
         imageUploadURL:"http://localhost:8080/image/uploadPostImage",
    });
}

// $
function loadData() {
    loadEditor();
    blockId = getQueryVariable("id");
     checkLogin();

    $.post({
        url: backBaseUrl + "/block/init-page",

        data: {
            "id":blockId
        },
        success: function (data) {

            // 加载版块信息，今日发帖数
            console.log(data);
            loadBlockInfo(data);
            // //加载所有版主信息
            loadBlockAdminList(data);
            // // 加载所有的分类
            loadClazzList(data);
            // // 加载一次所有帖子分页
            loadPostsAndPager(data);
            // // ====发帖
            // // 可以保存帖子
        },error:function (){
            layer.msg("版块信息加载失败,将在3秒后跳转回上一页");
            window.setTimeout(function (){
                window.history.back();
            },3000);
        }
    })
    //检查用户是不是被禁言了
    if(user !== undefined){
        console.log(user);
        checkIfUserBanned(user.base.id);

    }
}


/**
 * 如果用户没有登录，就禁用用户发帖的权限
 * 
 * 
 * 
 * */
function checkLogin(){
    // console.log("checking login")
    $.post({
        url: 'http://localhost:8080/login/checkLogin',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (msg) {
            let user = msg.data.user;
        //    user是
            if( user === undefined){
                $("#new-post-div").empty();
            }

            if(user !== undefined && user !== null){ console.log("user saved"); window.user = user;}
            // console.log(window.user)
        }, error: function (error) {
            layer.msg("公告获取失败~");
            console.log(error)
        }
    })
}

function loadBlockInfo(msg) {
    //先查询版块信息，再查询今天的发帖数
    let block = msg.data.block;
    // console.log(msg)
    // 置入数据
    $(".bc-nav-now").text(block.name);
    $("#title h2").text(block.name);
    // console.log(block.post_count)
    $("#total-post").append(block.post_count);
    let count = msg.data.todayPostCount;
    $("#today-post").append(count);
    blockId = block.id;
    search_data.blockId=blockId;
}

function loadBlockAdminList(msg) {
    let list = msg.data.blockAdminList;
    // console.log(list)
    // 置入数据
    $(list).each(function (i, e) {
        let str = "<div class='post-admin-item'><a href='../user/detail.html?id=" + e.id + "'><span>" + e.username + "</span></a>,</div>"
        $(".post-admin-list").append(str);
    })
}

function loadClazzList(msg) {
    let list = msg.data.classInfoList;
    let activeOne = parseInt(getQueryVariable("active_class_id"));
    let clazzList = $(".clazz-list");
    clazzList.html("");
    let s = "<div class='clazz-item";
    if (activeOne === false || activeOne === 0) {
        s += " my-button-active'"
    } else {
        s += " my-button'";
    }
    s += " onclick='changeClazz(0)' value='0'>全部</div>";
    clazzList.append(s);
    // 置入数据
    $(list).each(function (i, e) {
        let str = "<div class='clazz-item ";
        if (e.id === activeOne) {
            str += "my-button-active'";
        } else {
            str += "my-button'";
        }
        str += " onclick='changeClazz(" + e.id + ")' value='" + e.id + "'>" + e.name + "</div>";
        clazzList.append(str);
    })
    let cList = msg.data.classInfoList;
    $(cList).each(function (i, e) {
        let str = "<option name='post-clazz-item' class='post-clazz-item' value='" + e.id + "'>"
            + e.name + "</option>";
        $("#new-post-clazz-div select").append(str);
    })
}

function loadPostsAndPager(msg) {
    let list = msg.data.postList;
    // 添加所有的帖子
    loadPostListBase(list);
    attachPager(msg.data.pageList, 1);
}
// ==========================
//      加载所有的帖子，带清空列表
function loadPostListWithClear(postList) {
    // 清空列表，调用base
    $(".post-list-content").html("");
    loadPostListBase(postList);
}
// ==========================
//      直接把帖子附加进列表，不清空
function loadPostListBase(postList) {
    $(postList).each(function (i, e) {
        let str = "<div class='post-item'>";
        str += "<a href='../post/detail.html?id=" + e.id + "'><span class='post-name'>";
        console.log(e.state)
        if((e.state >> 2) & 1 === 1){
            //置顶贴
            str += "<span  class='layui-badge'>置顶</span>";
        }
        if((e.state >> 1) & 1 ===    1){
            str += "<span  class='layui-badge layui-bg-orange'>精华</span>"
        }
        str += "[" + e.className + "]" + e.title + "</span></a>";
        str += "<span class='author-name'>" + "<a href='../user/detail.html?id=" + e.authorId + "'>" + e.authorName + "</a>";
        str += "<span class='post-time' >" + e.createTime + "</span>" + "</span>";
        str += "<span class='reply-count'>" + e.replyCount + "</span>";
        $(".post-list-content").append(str);
    })
}

// ==========================
//      点击标签改变分类，使用ajax，不重新加载页面
function changeClazz(clazzId) {
    //1--将标签切换
    //2清除激活分类
    //3将当前分类设置为激活
    // 4:取得所有clazzitem,如果其拥有my-button-active，移除，设置为mybutton
    // 5:遍历clazzitem，当其value为clazzId,取消其mybtn，设置active
    let clazzitems = $(".clazz-item");
    console.log("changed")
    let v = $(".clazz-list .my-button-active");
    v.removeClass("my-button-active");
    v.addClass("my-button");
    // success V
    clazzitems.each(function (i, e) {
        if ($(e).attr("value") == clazzId) {
            $(e).removeClass("my-button");
            $(e).addClass("my-button-active");
        }
    })
    window.clazzId = clazzId;
    search_data = {
        blockId:blockId,
        classInfoId:clazzId
    }

    console.log()
    // 直接加载所有的帖子
    searchPostBase(1,false);
}

function search() {
    // 取得所有字段
    let postName = $("#post-name").val();
    let posterName = $("#poster-name").val();
    let inDate = $("#in-date").val();
    let conditions = $(".search-condition-group");

    // 拼装条件
    let data = {
        blockId: blockId,
        classInfoId: clazzId
    };
    let wait = false;
    if (conditions[0].checked) {
        data.title = postName;
        if(postName.length === 0){
            wait = true;
        }
    }
    if (conditions[1].checked) {
        data.authorName = posterName;
        if(posterName.length === 0){
            wait = true;
        }
    }
    if (conditions[2].checked) {
        data.createTime = inDate;
        if(inDate.length === 0){
            wait = true;
        }
    }
    if(wait === true){
        layer.msg("打勾的字段不能为空")
        return;
    }
    // 保存字段
    search_data = data;
    // 发送ajax请求，获取第一页
    console.log(search_data)
    searchPostBase(1,false);
}

function searchPostOrderBy(conditionName) {
    if (conditionName == 'time') {
        search_data.orderByCreateTime = true;
        search_data.orderByReplyCount = false;
    }
    if (conditionName == 'reply_count') {
        search_data.orderByReplyCount = true;
        search_data.orderByCreateTime = false;

    }
    searchPostBase(1,false);
}

function searchPostBase(page, append) {
    search_data.from = (page - 1) * 10;
    search_data.numPerPage = 10;
    search_data.curPage = page;
    $.ajax({
        url: 'http://localhost:8080/post/page',
        method: 'POST',
        data: search_data,
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (msg) {
            console.log(msg);
            if (append) {
                loadPostListBase(msg.data.postList);
            } else {
                loadPostListWithClear(msg.data.postList);
            }
            attachPager(msg.data.pageList, page);
        }, error: function (error) {
            layer.msg("帖子获取失败~")
        }
    });
}

function attachPager(pageList, num) {
    $(".page-list").html("");
    maxPage = parseInt(pageList[pageList.length - 1]);
    $(pageList).each(function (i, e) {
        let str = "<div class="
        if (e === num.toString()) {
            str += "'my-button-now'";
        } else {
            str += "'my-button'";
        }
        if (e !== '...') {
            str += "onclick='loadPage(" + e + ")'"
        }
        str += "/>" + e + "</div>";
        $(".page-list").append(str);
    })
}

function lastPage() {
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage <= 1) {
        // layer.msg("没有了");
        return;
    }
    loadPage(nowPage - 1);
}

function nextPage() {

    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        // layer.msg("没有了");
        console.log("没有了 ")
        return;
    }
    loadPage(nowPage + 1);
}

function jumpToPage() {
    let tPage = $("#jump-input").val();
    console.log(tPage);
    let page = parseInt(tPage);
    console.log(typeof (page))
    console.log(page)
    if (page < 1 || page > maxPage || isNaN(page)) {
        return;
    }
    loadPage(page);
}

function loadPage(page){
    searchPostBase(page);
}

function appendNextPage(){
    let tPage = $(".my-button-now").text();
    console.log(tPage)
    let nowPage = parseInt(tPage);
    if (nowPage >= maxPage) {
        // layer.msg("没有了");
        console.log("没有了 ")
        return;
    }
    searchPostBase(nowPage+1,true);
}

function checkPostTitleLen(){
    let title = $("#new-post-title");
    let maxLen = 80;
    if(title.val().length > maxLen){
        title.val(title.val().substring(0,maxLen))
    }
    $("#title-tip").text("还能输入" + (maxLen - title.val().length ) + '字');
}

function sendPost(){
    //获取所有信息
//    存入对象，并把对象发送给服务器
    let post_btn = $("#post-btn");

    let clazzId= $("#new-post-clazz option:selected").val();
    let title= $("#new-post-title").val();
    let content = window.editor.getMarkdown();
    console.log(title.length)
    console.log(content.length)
    if(title.length === 0){
        layer.msg("帖子名不能为空！")
        return;
    }
    if(content.length === 0){
        layer.msg("帖子内容不能为空！")
        return;
    }
    if(user == null){
        layer.msg("您还未登录！")
        return;
    }
    if(blockId === 0 || clazzId === 0){
        layer.msg("数据获取失败！请刷新重试");
        return;
    }

    post_btn.attr("disabled",true);
    post_btn.text("发帖中..");
    $.post({
        url:'http://localhost:8080/post/postOne',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        data:{
            "userId": user.base.id,
            "blockId": blockId,
            "clazzId":clazzId,
            "title":title,
            "content":content
        },success: function (msg){
            //0： 发帖成功
            if(msg.code === 0){
                layer.msg("发帖成功！")
                window.location.reload();
            }else if(msg.code === -1){
                layer.msg(msg.msg);
                post_btn.css("disable",false);
                post_btn.text("发帖");
            }
        },error:function (error){
            layer.confirm("遇到了一些问题T-T，请你重试，报错信息已经打印到控制台")
            post_btn.css("disable",false);
            post_btn.text("发帖");
            console.log(error);
        }
    });
}